package com.hiray.demos.etc.room

import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.room.*
import android.content.Context


@Entity(tableName = "Article")
class Article {
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
    var title: String
    var content: String


    constructor(id: Long, title: String, content: String) {
        this.id = id
        this.title = title
        this.content = content
    }
}

@Dao
interface ArticleDao {

    @Update
    fun updateArticle(article: Article)

    @Insert
    fun createArticle(article: Article): Long

    @Query("SELECT * FROM ARTICLE")
    fun getArticle(): List<Article>
}

@Database(entities = [Article::class], version = 1, exportSchema = false)
abstract class AppDataBase : RoomDatabase() {

    abstract fun articleDao(): ArticleDao

    companion object {
        var _INSTANCE: AppDataBase? = null

        fun getInstance(ctx: Context): AppDataBase {
            if (_INSTANCE == null)
                _INSTANCE = Room.databaseBuilder(ctx, AppDataBase::class.java, "Rom_Article")
                        .allowMainThreadQueries()
                        .addCallback(object : Callback() {
                            override fun onCreate(db: SupportSQLiteDatabase) {
                                super.onCreate(db)
                            }

                        })
                        .build()
            return _INSTANCE as AppDataBase

        }
    }
}